package com.yangjunli.bishe.Interceptor;

import com.google.common.base.Strings;
import com.yangjunli.bishe.core.RequestHolder;
import com.yangjunli.bishe.core.ReturnT;
import com.yangjunli.bishe.entity.User;
import com.yangjunli.bishe.service.IUserService;
import com.yangjunli.bishe.utils.JacksonUtil;
import com.yangjunli.bishe.utils.tokenUtils;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;


/**
 * @ Author kn
 * @ Description : 拦截器统一处理accesstoken
 * @ Date 2019/9/3 11:28
 */
@SuppressWarnings("ALL")
@Component
@Slf4j
public class AccessTokenInterceptor implements HandlerInterceptor {

    @Autowired
    IUserService iUserService;


    private final static String FAILED = "failed";  //失败

    @SuppressWarnings("AlibabaUndefineMagicConstant")
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
        try {
            //过滤掉 log Regist
            String requestURI = request.getRequestURI();

            if (requestURI.indexOf("login") != -1 || requestURI.indexOf("regist") != -1  ) {
                return true;
            }

//            String accessToken = request.getHeader("accessToken");
//            if (Strings.isNullOrEmpty(accessToken)) {
//                response.setContentType("application/json;charset=utf-8");
//                response.getWriter().write(JacksonUtil.writeValueAsString(new ReturnT(100, "accessToken is required")));
//                return false;
//            }
//            log.info("AccessTokenInterceptor Request path:{}", request.getRequestURI());
//            Enumeration<String> parameterNames = request.getParameterNames();
//            while (parameterNames.hasMoreElements()) {
//                String name = parameterNames.nextElement();
//                log.info("AccessTokenInterceptor {}:{}", name, request.getParameter(name));
//            }
//            Claims claims = tokenUtils.parseJWT(accessToken, "");
            Object id1 = request.getSession().getAttribute("userid");

            if(id1 != null){
                Integer id = Integer.valueOf(id1.toString());
                User user = iUserService.getById(id);
                if(user == null){
                    response.setContentType("application/json;charset=utf-8");
                    response.getWriter().write(JacksonUtil.writeValueAsString(new ReturnT(100, "accessToken is required")));
                    return false;
                }else {
                    RequestHolder.add(user);
                    RequestHolder.add(request);
                }

            }
            return true;
        } catch (IOException e) {
            log.error("AccessTokenInterceptor.preHandle.error{}", e);
        }
        return false;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object
            handler, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object
            handler, Exception ex) throws Exception {
        //关闭threadLocal
        RequestHolder.remove();
    }
}
